<template>
  <div class="login">
    <el-card style="width: 400px">
      <h2 style="text-align:center">登录</h2>
      <el-form :model="form" @submit.prevent="handleLogin">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" show-password />
        </el-form-item>
        <el-button type="primary" native-type="submit" style="width:100%">
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { jwtDecode } from 'jwt-decode'
import { login } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

interface JwtPayload {
  role: number   // 1-CUSTOMER 2-WAITER 3-MANAGER 4-ADMIN
}

const form = reactive({ username: '', password: '' })
const router = useRouter()
const auth = useAuthStore()

const handleLogin = async () => {
  try {
    const { data } = await login(form)
    auth.setToken(data.accessToken)

    // 1. 从 token 解析角色
    const payload = jwtDecode<JwtPayload>(data.accessToken)
    const roleMap: Record<number, string> = {
      1: 'CUSTOMER',
      2: 'WAITER',
      3: 'MANAGER',
      4: 'ADMIN'
    }
    const role = roleMap[payload.role] || 'WAITER'

    // 2. 按角色跳转
    if (role === 'ADMIN') {
  router.replace('/admin');
} else if (role === 'CUSTOMER') {
   router.replace('/select-store')
} else {
  router.replace('/dashboard');
}
    ElMessage.success('登录成功')
  } catch (e) {
    ElMessage.error('登录失败')
  }
}
</script>

<style scoped>
.login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f2f3f5;
}
</style>